﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Web.Api;
using System.Web.Http;
using System.Collections;
using System.Net.Http;
using System.Net;
using DotNetNuke.Entities.Modules;
using System.Collections.Specialized;
using System.Text;


namespace Christoc.Modules.discourseSSOdnn
{
    public class ssoController: DnnApiController
    {

        [AllowAnonymous]
        [HttpGet]
        public string Ping()
        {
            try
            {

                var mc = new DotNetNuke.Entities.Modules.ModuleController();
                var md = mc.GetModulesByDefinition(this.PortalSettings.PortalId, "discourseSSOdnn");
                var mdd = (DotNetNuke.Entities.Modules.ModuleInfo)md[0];
                var myModuleSettings = mc.GetModuleSettings(mdd.DesktopModule.ModuleID);

                
                string sso=  myModuleSettings["ssoSecret"].ToString();
                string rediretcturl = myModuleSettings["ssoDiscourceRedirectUrl"].ToString();

                if (!Uri.IsWellFormedUriString(rediretcturl, UriKind.RelativeOrAbsolute))
                {
                    throw new Exception(string.Format("Looks like your setting for Discource URL is not valid URI try change {0} to real URI", rediretcturl));
                }

                return string.Format("Hello there looks like you have setup API call right I have ssoSecret and redirect url is {0} ", rediretcturl);
                
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict)
                    {
                        Content = new StringContent("There is error in PING module "+ex.Message+" "+ex.StackTrace),
                        ReasonPhrase = "Critical Exception missing SSO setings"
                    });

            }

            //return "Hello from " + mdd.DesktopModule.ModuleName + " version: " + mdd.DesktopModule.Version;
            //objModules.UpdateModuleSetting(ModuleId, "surveyclosingdate", DotNetNuke.Common.Globals.DateToString(datClosingDate));
        }
        [DnnAuthorize]
        [HttpGet]
        public string PingLogIn()
        {
            return string.Format("Helo {0} You are able to call webapi as DNN authorizeed user, By the way server time is now: {1}",
                this.UserInfo.DisplayName, DateTime.Now.ToLongTimeString());
        }
        [DnnAuthorize]
        [HttpGet]
        public HttpResponseMessage login(string sso, string sig)
        {
            try
            {
                if (string.IsNullOrEmpty(sso) || string.IsNullOrEmpty(sig))
                    throw new Exception("SSO or SIG can not be empty");

                var mc = new DotNetNuke.Entities.Modules.ModuleController();
                var md = mc.GetModulesByDefinition(this.PortalSettings.PortalId, "discourseSSOdnn");
                var mdd = (DotNetNuke.Entities.Modules.ModuleInfo)md[0];
                var myModuleSettings = mc.GetModuleSettings(mdd.DesktopModule.ModuleID);


                string ssoSecret = myModuleSettings["ssoSecret"].ToString();
                string redirectUrl = myModuleSettings["ssoDiscourceRedirectUrl"].ToString();

                string checksum = ssoEngine.getHash(sso, ssoSecret);
                if (checksum != sig)
                    throw new Exception("Check sum of SSO is different from SIG");


                byte[] ssoBytes = Convert.FromBase64String(sso);
                string decodedSso = Encoding.UTF8.GetString(ssoBytes);

                NameValueCollection nvc = HttpUtility.ParseQueryString(decodedSso);

                string nonce = nvc["nonce"];

                 

                string email = this.UserInfo.Email;
                string username = this.UserInfo.Username;
                string name = this.UserInfo.DisplayName;
                string externalId = this.UserInfo.UserID.ToString();

                string returnPayload = "nonce=" + HttpUtility.UrlEncode(nonce) +
                                        "&email=" + HttpUtility.UrlEncode(email) +
                                        "&external_id=" + HttpUtility.UrlEncode(externalId) +
                                        "&username=" + HttpUtility.UrlEncode(username) +
                                        "&name=" + HttpUtility.UrlEncode(name);

                string encodedPayload = Convert.ToBase64String(Encoding.UTF8.GetBytes(returnPayload));
                string returnSig = ssoEngine.getHash(encodedPayload, ssoSecret);

                redirectUrl +=  "/session/sso_login?sso=" + encodedPayload + "&sig=" + returnSig;

                var response = Request.CreateResponse(HttpStatusCode.Moved);
                response.Headers.Location = new Uri(redirectUrl);
                return response;
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict)
                {
                    Content = new StringContent("There is error in Login module " + ex.Message + " " + ex.StackTrace),
                    ReasonPhrase = "Critical Exception missing SSO setings",
                    StatusCode= HttpStatusCode.InternalServerError

                });

            }
            
        }

    }

}


